<template>
  <div class="sidebar" :class="{ 'sidebar-collapsed': isSidebarCollapsed }">
    <!-- 侧边栏头部 -->
    <div class="sidebar-header">
      <div class="logo-section" v-if="!isSidebarCollapsed">
        <img src="@/assets/logo.png" alt="店小二Agent" width="40" height="40" />
        <span class="logo-text">店小二Agent</span>
      </div>
      <div class="logo-section collapsed" v-else>
        <img src="@/assets/logo.png" alt="店小二Agent" width="32" height="32" />
      </div>

      <!-- 收起/展开按钮 -->
      <el-button
        class="collapse-btn"
        :icon="isSidebarCollapsed ? Expand : Fold"
        @click="emit('toggle-sidebar')"
        circle
        size="small"
      />
    </div>

    <!-- 用户信息 -->
    <div class="user-info" v-if="!isSidebarCollapsed">
      <div class="user-avatar">
        <el-icon><User /></el-icon>
      </div>
      <div class="user-details">
        <h4>{{ userInfo.username }}</h4>
        <p>{{ userInfo.role === 'admin' ? '管理员' : '用户' }}</p>
      </div>
    </div>

    <!-- 导航菜单 -->
    <div class="sidebar-nav">
      <el-menu
        :default-active="activeMenu"
        class="sidebar-menu"
        :collapse="isSidebarCollapsed"
        @select="handleMenuSelect"
      >
        <el-menu-item index="/dashboard/knowledge-bases">
          <el-icon><Document /></el-icon>
          <template #title>知识库</template>
        </el-menu-item>
        <el-menu-item index="/dashboard/ai-assistant">
          <el-icon><Service /></el-icon>
          <template #title>创建智能客服</template>
        </el-menu-item>
        <el-menu-item index="/dashboard/api-platform">
          <el-icon><Connection /></el-icon>
          <template #title>API开放平台</template>
        </el-menu-item>
        <el-menu-item index="/dashboard/mcp-market">
          <el-icon><Star /></el-icon>
          <template #title>MCP市场</template>
        </el-menu-item>
      </el-menu>

      <!-- New section for chat sessions -->
      <div class="chat-sessions-section">
        <div class="separator"></div> <!-- Separator -->
        <div class="section-title" v-if="!isSidebarCollapsed">我的会话</div>
        <el-button
          class="create-new-chat-button"
          @click="createNewChat"
          :class="{ 'collapsed': isSidebarCollapsed }"
        >
          <el-icon><Plus /></el-icon>
          <span v-if="!isSidebarCollapsed">新聊天</span>
        </el-button>

        <el-menu
          :default-active="activeChatSession"
          class="chat-session-menu"
          :collapse="isSidebarCollapsed"
        >
          <el-menu-item
            v-for="session in chatSessions"
            :key="session.id"
            :index="session.id"
            @click="selectChatSession(session.id)"
          >
            <el-icon><ChatDotRound /></el-icon>
            <template #title>
              <span class="chat-session-name">{{ session.name }}</span>
              <el-button
                class="delete-chat-button"
                :icon="Delete"
                circle
                size="small"
                @click.stop="deleteChatSession(session.id)"
              />
            </template>
          </el-menu-item>
        </el-menu>
      </div>
    </div>

    <!-- 侧边栏底部 -->
    <div class="sidebar-footer">
      <el-button
        class="logout-button"
        @click="handleLogout"
        :class="{ 'collapsed': isSidebarCollapsed }"
      >
        <el-icon><SwitchButton /></el-icon>
        <span v-if="!isSidebarCollapsed">退出登录</span>
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { v4 as uuidv4 } from 'uuid'
import {
  Expand,
  Fold,
  Document,
  ChatDotRound,
  Plus,
  Service,
  Connection,
  User,
  SwitchButton,
  Delete,
  Star
} from '@element-plus/icons-vue'

const props = defineProps({
  isSidebarCollapsed: Boolean
})

const emit = defineEmits(['toggle-sidebar', 'logout'])

const router = useRouter()
const route = useRoute()

// 用户信息
const userInfo = computed(() => {
  const stored = localStorage.getItem('userInfo')
  return stored ? JSON.parse(stored) : { username: '用户', role: 'user' }
})

const chatSessions = ref([])
const activeChatSession = ref('')

const activeMenu = computed(() => {
  // 只取/dashboard/xxx部分，忽略后续参数
  const path = route.path;
  if (path.startsWith('/dashboard/knowledge-bases')) return '/dashboard/knowledge-bases';
  if (path.startsWith('/dashboard/ai-assistant')) return '/dashboard/ai-assistant';
  if (path.startsWith('/dashboard/api-platform')) return '/dashboard/api-platform';
  if (path.startsWith('/dashboard/mcp-market')) return '/dashboard/mcp-market';
  return '';
});

onMounted(() => {
  loadChatSessions()
  // Set active chat session based on current route
  if (route.path.startsWith('/dashboard/chat')) {
    activeChatSession.value = route.query.id || ''
    // If no session is active or loaded, create a new one.
    if (!activeChatSession.value && chatSessions.value.length === 0) {
        createNewChat();
    } else if (!activeChatSession.value && chatSessions.value.length > 0) {
        // If no active session but sessions exist, navigate to the first one
        selectChatSession(chatSessions.value[0].id);
    }
  }
})

watch(chatSessions, (newSessions) => {
  localStorage.setItem('chatSessions', JSON.stringify(newSessions))
}, { deep: true })

const loadChatSessions = () => {
  const storedSessions = localStorage.getItem('chatSessions')
  if (storedSessions) {
    chatSessions.value = JSON.parse(storedSessions)
  }
}

// 处理菜单选择
const handleMenuSelect = (index) => {
  if (index === '/dashboard/api-platform') {
    router.push({ path: index });
    return;
  }
  if (index === '/dashboard/knowledge-bases' || index === '/dashboard/ai-assistant' || index === '/dashboard/mcp-market') {
    router.push({ path: index });
    return;
  }
  // 新增：API平台的接口文档菜单跳转到/api-docs
  if (index === '/api-docs') {
    router.push({ path: '/api-docs' });
    return;
  }
  if (!chatSessions.value.some(session => session.id === index)) {
    router.push({ path: index });
  }
}

// 创建新会话
const createNewChat = () => {
  const newUuid = uuidToNumber(uuidv4())
  const newSession = {
    id: String(newUuid),
    name: `新会话 ${chatSessions.value.length + 1}`
  }
  chatSessions.value.push(newSession)
  localStorage.setItem('user_uuid', String(newUuid)) // Set current active UUID
  router.push({ path: '/dashboard/chat', query: { id: newSession.id } })
  activeChatSession.value = newSession.id
}

// 选择现有会话
const selectChatSession = (sessionId) => {
  localStorage.setItem('user_uuid', sessionId) // Set current active UUID
  router.push({ path: '/dashboard/chat', query: { id: sessionId } })
  activeChatSession.value = sessionId
}

// 删除会话
const deleteChatSession = async (sessionIdToDelete) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除此会话吗？此操作将删除所有聊天记录且无法恢复。',
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const indexToDelete = chatSessions.value.findIndex(s => s.id === sessionIdToDelete)
    if (indexToDelete !== -1) {
      // 删除本地聊天记录
      localStorage.removeItem('chat_history_session_' + sessionIdToDelete)
      
      // 从会话列表中移除
      chatSessions.value.splice(indexToDelete, 1)
      ElMessage.success('会话已删除')

      // 如果删除的是当前活跃会话
      if (sessionIdToDelete === activeChatSession.value) {
        if (chatSessions.value.length > 0) {
          // 还有其他会话，选择第一个
          selectChatSession(chatSessions.value[0].id)
        } else {
          // 没有会话了，清空当前会话状态，跳转到首页
          activeChatSession.value = ''
          localStorage.removeItem('current_chat_session')
          router.push('/dashboard/knowledge-bases')
        }
      }
    }
  } catch {
    // 用户取消删除
    ElMessage.info('删除已取消')
  }
}

// Re-using uuidToNumber for consistency
const uuidToNumber = (uuid) => {
  let number = 0
  for (let i = 0; i < uuid.length && i < 6; i++) {
    const hexValue = uuid[i]
    number = number * 16 + (parseInt(hexValue, 16) || 0)
  }
  return number % 1000000
}

// 退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要退出登录吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 清除登录状态
    localStorage.removeItem('isLoggedIn')
    localStorage.removeItem('userInfo')
    localStorage.removeItem('rememberMe')
    localStorage.removeItem('user_uuid') // Clear current UUID
    localStorage.removeItem('chatSessions') // Clear all chat sessions
    chatSessions.value = [] // Clear in memory

    ElMessage.success('已退出登录')
    emit('logout'); // 告知父组件已退出登录
    router.push('/login')
  } catch {
    // 用户取消退出
  }
}
</script>

<style scoped>
/* 侧边栏样式 */
.sidebar {
  width: 240px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  flex-direction: column;
  transition: width 0.3s ease;
  position: relative;
  z-index: 1000;
}

.sidebar-collapsed {
  width: 64px;
}

.sidebar-header {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 10px;
}

.logo-section.collapsed {
  justify-content: center;
}

.logo-text {
  font-size: 18px;
  font-weight: bold;
  color: white;
}

.collapse-btn {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
}

.collapse-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

/* 用户信息 */
.user-info {
  padding: 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
}

.user-details h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 600;
}

.user-details p {
  margin: 0;
  font-size: 12px;
  opacity: 0.8;
}

/* 导航菜单样式 */
.sidebar-nav {
  flex: 1;
  padding: 20px 0;
  display: flex;
  flex-direction: column;
}

.sidebar-menu {
  background: transparent;
  border: none;
}

.sidebar-menu :deep(.el-menu-item) {
  color: rgba(255, 255, 255, 0.8);
  background: transparent;
  border: none;
  margin: 5px 10px;
  border-radius: 8px;
  height: 50px;
  line-height: 50px;
}

.sidebar-menu :deep(.el-menu-item:hover) {
  background: rgba(255, 255, 255, 0.1);
  color: white;
}

.sidebar-menu :deep(.el-menu-item.is-active) {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  font-weight: bold;
}

.sidebar-menu :deep(.el-menu-item .el-icon) {
  color: inherit;
  font-size: 18px;
}

/* New chat sessions section styles */
.chat-sessions-section {
  flex: 1;
  padding: 0 0 20px 0;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  max-height: calc(100vh - 400px); /* 限制最大高度，确保退出按钮可见 */
}

.separator {
  height: 1px;
  background-color: rgba(255, 255, 255, 0.1);
  margin: 15px 20px;
}

.section-title {
  font-size: 14px;
  font-weight: bold;
  color: rgba(255, 255, 255, 0.7);
  padding: 0 20px 10px 20px;
}

.create-new-chat-button {
  width: calc(100% - 40px);
  margin: 0 20px 10px 20px;
  background: rgba(255, 255, 255, 0.15);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.create-new-chat-button:hover {
  background: rgba(255, 255, 255, 0.25);
  color: white;
}

.create-new-chat-button.collapsed {
  width: 40px;
  padding: 0;
  margin: 0 auto 10px auto;
}

.chat-session-menu {
  background: transparent;
  border: none;
  flex: 1;
}

.chat-session-menu :deep(.el-menu-item) {
  color: rgba(255, 255, 255, 0.8);
  background: transparent;
  border: none;
  margin: 5px 10px;
  border-radius: 8px;
  height: 50px;
  line-height: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 15px;
}

.chat-session-menu :deep(.el-menu-item:hover) {
  background: rgba(255, 255, 255, 0.1);
  color: white;
}

.chat-session-menu :deep(.el-menu-item.is-active) {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  font-weight: bold;
}

/* Show delete button on hover of the menu item */
.chat-session-menu :deep(.el-menu-item:hover .delete-chat-button) {
  opacity: 1;
  pointer-events: auto;
  transform: translateX(0);
}

.chat-session-menu :deep(.el-menu-item .el-icon) {
  color: inherit;
  font-size: 18px;
}

.chat-session-name {
  flex-grow: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.delete-chat-button {
  margin-left: 10px;
  background: transparent;
  border: none;
  color: rgba(255, 255, 255, 0.6);
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.3s ease, transform 0.3s ease;
  transform: translateX(10px);
}

.delete-chat-button:hover {
  background: transparent;
  color: #f56c6c;
}

/* 侧边栏底部 */
.sidebar-footer {
  padding: 20px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.logout-button {
  width: 100%;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.logout-button:hover {
  background: rgba(255, 255, 255, 0.2);
  color: white;
}

.logout-button:hover {
  background: rgba(245, 108, 108, 0.2);
  color: #f56c6c;
}

.logout-button.collapsed {
  justify-content: center;
}

.logout-button .el-icon {
  font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    position: fixed;
    left: 0;
    top: 0;
    height: 100vh;
    z-index: 1000;
    transform: translateX(-100%);
    transition: transform 0.3s ease;
  }

  .sidebar.show {
    transform: translateX(0);
  }
}
</style> 